<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { modalFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { SpuCategoryTypeEnum } from '@/enums/spuEnum';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { SpuModule } = mcApi;
  const { SpuApi, CategoryApi } = SpuModule;

  const categoryId = ref<string>('');
  CategoryApi.getSpuCategoryPage({ type: SpuCategoryTypeEnum.RECHARGE }).then((res) => {
    categoryId.value = res?.items?.[0]?.id || '';
  });

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: modalFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const ifUpdate = ref<boolean>(false);
  const [registerModal, { setModalProps }] = useModalInner(async (data: any) => {
    await resetFields();
    ifUpdate.value = !!data.ifUpdate;
    setModalProps({
      minHeight: 50,
      confirmLoading: false,
      title: '充值配置',
      destroyOnClose: true,
    });
    const record = data?.record || {};
    const { giftAmount } = record?.specialInfo || {};
    giftAmount && (record.giftAmount = giftAmount);
    !unref(ifUpdate) && (record.sortNo = 1);
    await setFieldsValue(record);
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      await validate();
      const values: any = getFieldsValue();
      const { name, stdSpecId, giftAmount, unitSellingPrice } = values;
      values.categoryId = categoryId.value;
      values.standardSpecList = [
        {
          name,
          id: stdSpecId,
          unitSellingPrice,
          specialInfo: { giftAmount },
        },
      ];
      delete values['stdSpecId'];
      setModalProps({ confirmLoading: true });
      const fun = unref(ifUpdate) ? SpuApi.updateSpu : SpuApi.createSpu;
      await fun(values);
      createMessage.success(`${unref(ifUpdate) ? '编辑' : '新增'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
